﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
using System.IO;

namespace Gedea.Service
{
    public class DataEncryption
    {
        private static Aes aes;

        static DataEncryption()
        {
            aes = Aes.Create();
            //TO DO cambiar estos valores!!!!
            string password = "fHa4ASjsnYj02jd95Sqk9d8E9Dj9xadR";
            string salt = "xSfjdA7b9udv1hw3";

            PasswordDeriveBytes pdb = new PasswordDeriveBytes(Encoding.ASCII.GetBytes(password), Encoding.ASCII.GetBytes(salt), "MD5", 3);

            aes.KeySize = 256;
            aes.Key = pdb.GetBytes(32);
            aes.IV = pdb.GetBytes(16);
            aes.Mode = CipherMode.CBC;
            aes.Padding = PaddingMode.ISO10126;
        }

        public static byte[] Encrypt(string source)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(Encoding.ASCII.GetBytes(source), 0, Encoding.ASCII.GetBytes(source).Length);
                }

                return ms.ToArray();
            }
        }

        public static string Decrypt(byte[] source)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
                {
                    cs.Write(source, 0, source.Length);
                }

                return Encoding.ASCII.GetString(ms.ToArray());
            }
        }
    }
}
